<!-- 客户管理-客户列表 -->
<template>
  <div class="client-black-list">
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    </pageHeader>
    <a-space class="client-black-list-header">
      <div>
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入想要搜索的内容"
          search-button
          @change="search"
          v-model="searchVal"
        />
        <a-popover position="right">
          <icon-exclamation-circle
            :style="{
              position: 'relative',
              marginLeft: '10px',
              color: 'red',
            }"
            :size="16"
          />
          <template #content>
            <p> 只可以根据客户名称、编号、联系电话、联系人、区域和行业搜索 </p>
          </template>
        </a-popover>
      </div>

      <div style="margin-left: 30px">
        <a-space>
          <a-button status="warning" @click="getDeriveData">
            <template #icon>
              <icon-export rotate="-90" />
            </template>
            <template #default>导出</template>
          </a-button>
          <a-button type="primary" @click="showFormHeaderSetting"
            >表头设置</a-button
          >
        </a-space>
      </div>
    </a-space>
    <div style="padding: 0px 15px">
      <tableTurn :tableData="getClientListData" :args="args" ref="tableTurnRef">
        <a-table-column :width="80" align="center">
          <template #title> 序号 </template>
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column
          :title="item.name"
          v-for="(item, index) in selectedHeader"
          :key="index"
          :data-index="item.code"
          align="center"
          :width="200"
          :fixed="item.code === 'salesName' ? 'right' : ''"
        >
          <!-- 创建时间item -->
          <template v-if="item.code === 'createdAt'" #cell="{ record }">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
          </template>
        </a-table-column>

        <!-- 操作item -->
        <a-table-column align="center" :width="300" fixed="right" title="操作">
          <template #cell="{ record, rowIndex }">
            <a-popconfirm
              @ok="changeBlack(record.id, rowIndex)"
              content="确定要解除黑名单吗"
              type="warning"
            >
              <a-button type="text">解除黑名单</a-button>
            </a-popconfirm>
            <a-button type="text" @click="goDetail(record.id)">详情</a-button>
            <a-popconfirm
              @ok="deleteItem(record.id, rowIndex)"
              content="确定删除吗"
              type="error"
            >
              <a-button
                type="text"
                :style="{
                  color: 'red',
                }"
                >删除</a-button
              >
            </a-popconfirm>
          </template>
        </a-table-column>
      </tableTurn>
    </div>

    <FormHeaderSetting
      v-model:visible="formHeaderSettingVisible"
      title="客户列表表头设置"
      :resultList="headerSetting.list"
      @headerSave="headerSave"
      :forbidList="forbidList"
    ></FormHeaderSetting>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watchEffect, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import {
    GetClientHeader,
    PutClientHeader,
    GetBlackClientList,
    PutClientState,
    DelClientList,
    PutClient2Black,
    GetClientBlacklistDeriveExcel,
  } from '@/api/order-management/client-management/client-list';
  import dayjs from 'dayjs';
  import cloneDeep from 'lodash.clonedeep';
  import { formHeaderSetting } from '@/types/global';

  const router = useRouter();
  const title = '黑名单列表';
  const breadCrumb = ['订单管理', '客户管理', '黑名单列表'];

  const headerSetting = reactive<any>({
    list: [],
  });

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (销售员)

  // 表格配置
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    // virtualListProps: '{height:400}',
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
  });
  let searchVal = ref(''); // 储存搜索框值
  let tableTurnRef: any = ref(); // 储存table的ref
  let isFirstSelect = ref(true);
  // 获取客户列表数据
  const getClientListData = async (pageData?: any) => {
    isFirstSelect.value = false;
    try {
      const res = await GetBlackClientList({
        ...pageData,
        keyWord: searchVal.value,
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 搜索框
  const search = async () => {
    tableTurnRef.value.loadData();
  };

  // watchEffect(() => {
  //   if (!isFirstSelect.value && searchVal.value === '')
  //     tableTurnRef.value.loadData();
  // });

  const columns = [
    {
      name: '客户编号',
      code: 'customerNumber',
      isDefault: 1,
    },
    {
      name: '客户名称',
      code: 'name',
      isDefault: 1,
    },
    {
      name: '客户级别',
      code: 'levelName',
      isDefault: 1,
    },
    {
      name: '联系电话',
      code: 'customerContactPhone',
      isDefault: 1,
    },
    {
      name: '联系邮箱',
      code: 'customerEmail',
      isDefault: 1,
    },
    {
      name: '省市区',
      code: 'city',
      isDefault: 1,
    },
    {
      name: '详细地址',
      code: 'address',
      isDefault: 1,
    },
    {
      name: '客户来源',
      code: 'sourceName',
      isDefault: 1,
    },
    {
      name: '客户行业',
      code: 'industry',
      isDefault: 1,
    },
    {
      name: '客户类别',
      code: 'customerTypeName',
      isDefault: 1,
    },
    {
      name: '联系人',
      code: 'contactName',
      isDefault: 1,
    },
    {
      name: '联系人职位',
      code: 'contactPosition',
      isDefault: 1,
    },
    {
      name: '联系人部门',
      code: 'contactDepartment',
      isDefault: 1,
    },
    {
      name: '联系人手机',
      code: 'contactPhone',
      isDefault: 1,
    },
    {
      name: '销售责任人',
      code: 'salesName',
      isDefault: 1,
    },
  ];
  // 获取表头设置列表
  const HeadersId = ref();
  const getHeaders = async () => {
    try {
      const res = await GetClientHeader({ listType: 2 });
      if (res.id === 0) {
        headerSetting.list = columns;
      } else {
        headerSetting.list = res.extends;
      }
      // headerSetting.list = res.extend;
      // HeadersId.value = res.id;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: formHeaderSetting['list'] = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  // // 去往对应的详情页面
  // const goDetail = (id: number) => {
  //   router.push({
  //     name: 'ClientInfoDetail',
  //     query: {
  //       id,
  //     },
  //   });
  // };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      const data = {
        listType: 2,
        extend: JSON.stringify(headerList),
      };
      await PutClientHeader(data);
      headerSetting.list = [...headerList];
    } catch (err: unknown) {
      console.log(err);
    }
  };
  // 储存客户人员信息
  const clientList = reactive([]);

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  let currId = ref(-1); // 储存当前选中的id

  // 去往对应的详情页面
  const goDetail = (id: number) => {
    router.push({
      name: 'ClientInfoDetail',
      query: {
        id,
      },
    });
  };

  // 删除一项
  const deleteItem = async (id: number, rowIndex: number) => {
    try {
      await DelClientList({
        id,
      });
      tableTurnRef.value.tableList.splice(rowIndex, 1);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 解除黑名单
  const changeBlack = async (id: number, rowIndex: number) => {
    try {
      await PutClient2Black({
        id,
      });
      tableTurnRef.value.tableList.splice(rowIndex, 1);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const getDeriveData = () => {
    GetClientBlacklistDeriveExcel('客户黑名单模板');
  };
</script>

<style scoped lang="less">
  .client-black-list {
    :deep(.arco-space) {
      // justify-content: space-between;
    }
    :deep(.arco-space-horizontal .arco-space-item) {
      // margin-left: 50px;
    }
    &-header {
      width: 100%;
      padding: 15px;
      display: flex;
      justify-content: space-between;
      // margin-bottom: 10px;
      // margin-top: 10px;
      :deep(.arco-btn-secondary) {
        // color: #165dff;
        // margin-right: 20px;
      }
    }
  }
</style>
